<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="itemName">
        <el-input v-model="queryParams.itemName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="项目品类" prop="type">
        <el-select 
          v-if="typeOptions.length > 0"
          v-model="queryParams.type" 
          placeholder="请选择项目品类" 
          clearable 
          filterable
          style="width: 100%"
          @change="handleTypeChange">
          <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-select 
          v-else
          v-model="queryParams.type" 
          placeholder="加载中..." 
          disabled
          style="width: 100%">
        </el-select>
      </el-form-item>
      <el-form-item label="项目状态" prop="status">
        <el-select 
          v-if="statusOptions.length > 0"
          v-model="queryParams.status" 
          placeholder="请选择项目状态" 
          clearable 
          filterable 
          style="width: 100%"
          @change="handleStatusChange">
          <el-option v-for="s in statusOptions" :key="s.value" :label="s.label" :value="s.value" />
        </el-select>
        <el-select 
          v-else
          v-model="queryParams.status" 
          placeholder="加载中..." 
          disabled
          style="width: 100%">
        </el-select>
      </el-form-item>
      <el-form-item label="是否线上展示" prop="onlineFlag">
        <el-select 
          v-if="sysYesNo.length > 0"
          v-model="queryParams.onlineFlag" 
          placeholder="请选择是否线上展示" 
          clearable 
          filterable
          style="width: 100%"
          @change="handleOnlineFlagChange">
          <el-option v-for="dict in sysYesNo" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
        <el-select 
          v-else
          v-model="queryParams.onlineFlag" 
          placeholder="加载中..." 
          disabled
          style="width: 100%">
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain :icon="Plus" @click="handleAdd"
          v-hasPermi="['system:shopItem:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain :icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:shopItem:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain :icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:shopItem:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain :icon="Download" :loading="exportLoading" @click="handleExport"
          v-hasPermi="['system:shopItem:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="shopItemList" @selection-change="handleSelectionChange"
      :row-style="{ height: '60px' }" :cell-style="{ padding: '8px 0' }" style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="项目名称" align="center" prop="itemName" show-overflow-tooltip min-width="120" />
      <el-table-column label="项目简介" align="center" prop="itemRemark" show-overflow-tooltip min-width="180" />
      <el-table-column label="项目价格" align="center" prop="itemPrice" min-width="100">
        <template #default="scope">
          ￥{{ Number(scope.row.itemPrice).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="项目品类" align="center" prop="type" show-overflow-tooltip min-width="100">
        <template #default="scope">
          {{ typeFormat(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="是否推荐" align="center" prop="referrerFlag">
        <template #default="scope">
          {{ referrerFlagFormat(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="是否线上展示Y是N否" align="center" prop="onlineFlag">
        <template #default="scope">
          {{ onlineFlagFormat(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="项目状态" align="center" prop="status">
        <template #default="scope">
          {{ statusFormat(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="text" :icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:shopItem:edit']">修改</el-button>
          <el-button type="text" :icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:shopItem:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改项目管理对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="itemName">
              <el-input v-model="form.itemName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目品类" prop="type">
              <el-select v-model="form.type" placeholder="请选择项目品类" style="width: 100%">
                <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider>返佣设置</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="返佣类型" prop="commissionType">
              <el-radio-group v-model="form.commissionType" @change="handleCommissionTypeChange">
                <el-radio-button label="fixed">固定金额</el-radio-button>
                <el-radio-button label="percentage">百分比</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="等级1返佣" prop="sharePercent1">
              <el-input-number 
                v-model="form.sharePercent1" 
                :min="0" 
                :precision="2" 
                :step="form.commissionType === 'percentage' ? 0.1 : 0.01"
                :max="form.commissionType === 'percentage' ? 1 : undefined"
                :placeholder="form.commissionType === 'percentage' ? '请输入等级1返佣百分比' : '请输入等级1返佣金额'"
                style="width: 100%">
                <template #suffix v-if="form.commissionType === 'percentage'">%</template>
              </el-input-number>
              <div class="el-form-item__hint" v-if="form.commissionType === 'percentage'">
                请输入返佣比例(值在0-1之间,例如:0.05)
              </div>
              <div class="el-form-item__hint" v-else>
                请输入返佣金额,值大于0
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="等级2返佣" prop="sharePercent2">
              <el-input-number 
                v-model="form.sharePercent2" 
                :min="0" 
                :precision="2" 
                :step="form.commissionType === 'percentage' ? 0.1 : 0.01"
                :max="form.commissionType === 'percentage' ? 1 : undefined"
                :placeholder="form.commissionType === 'percentage' ? '请输入等级2返佣百分比' : '请输入等级2返佣金额'"
                style="width: 100%">
                <template #suffix v-if="form.commissionType === 'percentage'">%</template>
              </el-input-number>
              <div class="el-form-item__hint" v-if="form.commissionType === 'percentage'">
                请输入返佣比例(值在0-1之间,例如:0.05)
              </div>
              <div class="el-form-item__hint" v-else>
                请输入返佣金额,值大于0
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="等级3返佣" prop="sharePercent3">
              <el-input-number 
                v-model="form.sharePercent3" 
                :min="0" 
                :precision="2" 
                :step="form.commissionType === 'percentage' ? 0.1 : 0.01"
                :max="form.commissionType === 'percentage' ? 1 : undefined"
                :placeholder="form.commissionType === 'percentage' ? '请输入等级3返佣百分比' : '请输入等级3返佣金额'"
                style="width: 100%">
                <template #suffix v-if="form.commissionType === 'percentage'">%</template>
              </el-input-number>
              <div class="el-form-item__hint" v-if="form.commissionType === 'percentage'">
                请输入返佣比例(值在0-1之间,例如:0.05)
              </div>
              <div class="el-form-item__hint" v-else>
                请输入返佣金额,值大于0
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="等级4返佣" prop="sharePercent4">
              <el-input-number 
                v-model="form.sharePercent4" 
                :min="0" 
                :precision="2" 
                :step="form.commissionType === 'percentage' ? 0.1 : 0.01"
                :max="form.commissionType === 'percentage' ? 1 : undefined"
                :placeholder="form.commissionType === 'percentage' ? '请输入等级4返佣百分比' : '请输入等级4返佣金额'"
                style="width: 100%">
                <template #suffix v-if="form.commissionType === 'percentage'">%</template>
              </el-input-number>
              <div class="el-form-item__hint" v-if="form.commissionType === 'percentage'">
                请输入返佣比例(值在0-1之间,例如:0.05)
              </div>
              <div class="el-form-item__hint" v-else>
                请输入返佣金额,值大于0
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="项目简介" prop="itemRemark">
          <el-input v-model="form.itemRemark" type="textarea" :rows="3" placeholder="请输入项目简介" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目价格" prop="itemPrice">
              <el-input-number 
                v-model="form.itemPrice" 
                :min="0" 
                :precision="2" 
                placeholder="请输入项目价格"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目排序" prop="sortNo">
              <el-input-number 
                v-model="form.sortNo" 
                :min="0" 
                placeholder="请输入项目排序"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="是否线上销售" prop="onlineFlag">
          <el-radio-group v-model="form.onlineFlag">
            <el-radio v-for="dict in sysYesNo" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="项目头图" prop="headerImg">
          <image-upload v-model="form.headerImg" :limit="1" />
        </el-form-item>

        <el-form-item label="详情图片" prop="detailImg">
          <image-upload v-model="form.detailImg" :limit="5" />
        </el-form-item>

        <el-form-item label="项目描述" prop="itemDetail">
          <editor v-model="form.itemDetail" :min-height="192" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否推荐" prop="referrerFlag">
              <el-radio-group v-model="form.referrerFlag">
                <el-radio v-for="dict in sysYesNo" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="s in statusOptions" :key="s.value" :value="s.value">{{ s.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ShopItem">
import { ref, reactive, toRefs, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Download } from '@element-plus/icons-vue'
import { listShopItem, getShopItem, delShopItem, addShopItem, updateShopItem, exportShopItem, getsysYesNo, getShopItemType, getShopItemDict } from "@/api/system/shopItem";
import { parseTime } from '@/utils/ruoyi'
// dicts will be loaded from API
import { download } from '@/utils/request'
import { formatDate } from '@/utils/index'


const queryFormRef = ref()
const formRef = ref()

// dictionary options loaded from backend
const sysYesNo = ref([])
const typeOptions = ref([])
const statusOptions = ref([])

/** 项目品类格式化 */
function typeFormat(row) {
  const opt = typeOptions.value.find(i => i.value === String(row.type))
  return opt ? opt.label : row.type
}

/** 是否推荐格式化 */
function referrerFlagFormat(row) {
  const opt = sysYesNo.value.find(i => i.value === String(row.referrerFlag))
  return opt ? opt.label : row.referrerFlag
}

/** 是否线上展示格式化 */
function onlineFlagFormat(row) {
  const opt = sysYesNo.value.find(i => i.value === String(row.onlineFlag))
  return opt ? opt.label : row.onlineFlag
}

/** 项目状态格式化 */
function statusFormat(row) {
  const opt = statusOptions.value.find(i => i.value === String(row.status))
  return opt ? opt.label : row.status
}
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)

const state = reactive({
  // 遮罩层
  loading: true,
  // 导出遮罩层
  exportLoading: false,
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  // 项目管理表格数据
  shopItemList: [],
  // 弹出层标题
  title: "",
  // 是否显示弹出层
  open: false,
  // 是否推荐字典
  referrerFlagOptions: [],
  // 是否线上展示Y是N否字典
  onlineFlagOptions: [],
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    itemName: null,
    type: undefined,
    referrerFlag: null,
    onlineFlag: undefined,
    status: undefined,
  },
  // 表单参数
  form: {},
  // 表单校验
  rules: {
    itemName: [
      { required: true, message: '项目名称不能为空', trigger: 'blur' }
    ],
    type: [
      { required: true, message: '请选择项目品类', trigger: 'change' }
    ],
    itemPrice: [
      { required: true, message: '项目价格不能为空', trigger: 'blur' },
      { type: 'number', min: 0, message: '项目价格必须大于0', trigger: 'blur' }
    ],
    onlineFlag: [
      { required: true, message: '请选择是否线上销售', trigger: 'change' }
    ],
    referrerFlag: [
      { required: true, message: '请选择是否推荐', trigger: 'change' }
    ],
    sharePercent1: [
      { required: true, message: '请输入等级1返佣', trigger: 'blur' },
      { type: 'number', min: 0, message: '返佣金额必须大于等于0', trigger: 'blur' }
    ],
    sharePercent2: [
      { required: true, message: '请输入等级2返佣', trigger: 'blur' },
      { type: 'number', min: 0, message: '返佣金额必须大于等于0', trigger: 'blur' }
    ],
    sharePercent3: [
      { type: 'number', min: 0, message: '返佣金额必须大于等于0', trigger: 'blur' }
    ],
    sharePercent4: [
      { type: 'number', min: 0, message: '返佣金额必须大于等于0', trigger: 'blur' }
    ]
  }
})

// 切换返佣类型
function handleCommissionTypeChange() {
  // 当切换类型时，可以在这里添加额外的逻辑
  console.log('Commission type changed to:', form.value.commissionType);
}

const { loading, exportLoading, showSearch, total, shopItemList, title, open, queryParams, form, rules } = toRefs(state)

/** 查询项目管理列表 */
function getList() {
  loading.value = true
  listShopItem(queryParams.value).then(response => {
    shopItemList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    itemName: null,
    type: null,
    itemRemark: null,
    itemPrice: null,
    itemVipPrice: null,
    bankDiscount: null,
    headerImg: null,
    detailImg: null,
    itemDetail: null,
    referrerFlag: null,
    onlineFlag: null,
    sortNo: null,
    status: "01", // 默认为上架状态
    commissionType: 'fixed', // 返佣类型：fixed-固定金额, percentage-百分比
    sharePercent1: 0,  // 等级1返佣
    sharePercent2: 0,  // 等级2返佣
    sharePercent3: 0,  // 等级3返佣
    sharePercent4: 0,  // 等级4返佣
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null
  }
  formRef.value?.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 项目状态选择变化处理 */
function handleStatusChange(value) {
  // 确保值的类型与选项值类型一致
  if (value !== null && value !== undefined && typeof value !== 'string') {
    queryParams.value.status = String(value)
  } else if (value === null || value === undefined) {
    queryParams.value.status = undefined
  }
}

/** 项目品类选择变化处理 */
function handleTypeChange(value) {
  // 确保值的类型与选项值类型一致
  if (value !== null && value !== undefined && typeof value !== 'string') {
    queryParams.value.type = String(value)
  } else if (value === null || value === undefined) {
    queryParams.value.type = undefined
  }
}

/** 是否线上展示选择变化处理 */
function handleOnlineFlagChange(value) {
  // 确保值的类型与选项值类型一致
  if (value !== null && value !== undefined && typeof value !== 'string') {
    queryParams.value.onlineFlag = String(value)
  } else if (value === null || value === undefined) {
    queryParams.value.onlineFlag = undefined
  }
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加项目管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const id = row?.id || ids.value[0]
  if (!id) {
    ElMessage.warning("请选择要修改的数据")
    return
  }
  // 先打开对话框
  open.value = true
  title.value = "修改项目管理"
  // 加载详情并回填表单
  getShopItem(id).then(res => {
    const d = res?.data || res || {}
    // 基础字段直接回填
    form.value = { ...form.value, ...d }
    // 规范化字典与数值类型为字符串（与选项一致）
    form.value.type = d.type != null ? String(d.type) : null
    form.value.referrerFlag = d.referrerFlag != null ? String(d.referrerFlag) : null
    form.value.onlineFlag = d.onlineFlag != null ? String(d.onlineFlag) : null
    form.value.status = d.status != null ? String(d.status) : form.value.status
    // 图片字段兼容数组/字符串
    const toCommaString = (v) => Array.isArray(v) ? v.join(',') : (v ?? null)
    form.value.headerImg = toCommaString(d.headerImg)
    form.value.detailImg = toCommaString(d.detailImg)
  })
}


/** 提交按钮 */
function submitForm() {
  formRef.value?.validate(valid => {
    if (valid) {
      const formData = { ...form.value }
      if (form.value.id != null) {
        updateShopItem(formData).then(response => {
          ElMessage.success("修改成功")
          open.value = false
          getList()
        })
      } else {
        addShopItem(formData).then(response => {
          ElMessage.success("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const idsToDelete = row.id || ids.value
  ElMessageBox.confirm('是否确认删除项目管理编号为"' + idsToDelete + '"的数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    return delShopItem(idsToDelete)
  }).then(() => {
    getList()
    ElMessage.success("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  const queryParams = { ...state.queryParams }
  ElMessageBox.confirm('是否确认导出所有项目管理数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    state.exportLoading = true
    const { pageNum, pageSize, ...filters } = queryParams
    return download('/shop/item/export', filters, `项目管理_${formatDate(new Date())}.xlsx`)
  }).finally(() => {
    state.exportLoading = false
  })
}

// 加载字典数据
function loadDicts() {
  return Promise.all([getsysYesNo(), getShopItemType(), getShopItemDict()])
    .then(([yesNoRes, typeRes, statusRes]) => {
      sysYesNo.value = (yesNoRes.data || []).map(p => ({ label: p.dictLabel, value: String(p.dictValue) }))
      typeOptions.value = (typeRes.data || []).map(p => ({ label: p.dictLabel, value: String(p.dictValue) }))
      statusOptions.value = (statusRes.data || []).map(p => ({ label: p.dictLabel, value: String(p.dictValue) }))
    })
    .catch(err => {
      // fallback: keep arrays empty and let UI handle it
      console.error('load dicts error', err)
    })
}

// 首先加载字典，再加载列表
loadDicts().then(() => getList())
</script>